package org.mybatis.generator.extend.servicegenerator;

import org.mybatis.generator.api.dom.java.*;

import java.util.Set;
import java.util.TreeSet;


/**
 * service实现 修改方法构造
 */
public class UpdateByPrimaryKeySelectiveMethodOfServiceGenerator extends AbstractJavaServiceMethodGenerator {

	public UpdateByPrimaryKeySelectiveMethodOfServiceGenerator() {
		super();
	}

	@Override
	public void addServiceElements(TopLevelClass topLevelClass) {
		Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
		FullyQualifiedJavaType parameterType;

		if (introspectedTable.getRules().generateRecordWithBLOBsClass()) {
			parameterType = new FullyQualifiedJavaType(introspectedTable.getRecordWithBLOBsType());
		} else {
			parameterType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
		}

		importedTypes.add(parameterType);

		Method method = new Method();
		//method.addAnnotation("@Transactional");
		method.setVisibility(JavaVisibility.PUBLIC);
		method.setReturnType(FullyQualifiedJavaType.getIntInstance());
		method.setName(introspectedTable.getUpdateByPrimaryKeySelectiveStatementId());
		method.addParameter(new Parameter(parameterType, "record")); //$NON-NLS-1$
		method.addAnnotation("@Override");
		
		// 方法内容
		FullyQualifiedJavaType mapper = new FullyQualifiedJavaType(introspectedTable.getMyBatis3JavaMapperType());
		StringBuffer bodyLineSB = new StringBuffer();
		bodyLineSB.append("return ");
		String shortName = mapper.getShortName();
		shortName = shortName.substring(0, 1).toLowerCase() + shortName.substring(1);
		bodyLineSB.append(shortName + "." + introspectedTable.getUpdateByPrimaryKeySelectiveStatementId() + "(record);");
		method.addBodyLine(bodyLineSB.toString());
		method.addJavaDocLine("/** 根据主键修改该记录 */");
		context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable);

		if (context.getPlugins().clientUpdateByPrimaryKeySelectiveMethodGenerated(method, topLevelClass, introspectedTable)) {
			topLevelClass.addImportedTypes(importedTypes);
			topLevelClass.addMethod(method);
		}
	}

}